#######################################################
# Example of DEVS Tennis Court Alarm Clock 
# Author: moonho.hwang@gmail.com
#   Date: Oct.19.2011
#######################################################

from XSY.DEVS.FDDEVS import *
from XSY.DEVS.SimEngine import SimEngine

class AlarmClock(FDDEVS):
   def __init__(self, n, parent=None):
      '''constructor'''
      FDDEVS.__init__(self, n, parent)
      self.phase = 'Normal'
      self.output = True
      self.addOutputPorts('!o')
      self.addInputPorts('?i')

   def delta_0(self):
      '''reset the initial state'''
      self.phase = 'Normal'

   def tau(self):
      '''lifespan scheduling function'''
      if self.phase == 'Alert':
         return 10
      else:
         return 50 

   def delta_x(self, x):
      '''external transition function'''
      if x.port == self.IP['?i']:
         self.output = not self.output
      return False

   def delta_y(self):
      '''output and internal transition function'''
      if self.phase == 'Normal':
         self.phase = 'Alert'
         if self.output:
            return PortValue(self.OP['!o'], True) # rising edge
      elif self.phase == 'Alert':
         self.phase = 'Normal'
         if self.output:
            return PortValue(self.OP['!o'], False) # downing edge
      pass

   def get_state(self):
      '''get state '''
      return self.phase, self.output

   def set_state(self, state):
      self.phase, self.output = state

#end of SVGClock

def inject_CB(md):
   '''inject CB'''
   return md, PortValue(md.IP['?i'])

def runSimulation(md):
   engine = SimEngine(md, inject_CB)
   engine.runInteractiveMenu()
############################################################################################################

if __name__ == '__main__':
   import pkg_resources
   print 'XSY version %s'% pkg_resources.get_distribution("XSY").version
   #print 'XSY.DEVS version %s'% pkg_resources.get_distribution("XSY.DEVS").version

   md = AlarmClock('clock')
   runSimulation(md)
   print "good bye~!" 
